package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private IAddressBookService addressBookService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IOrderDetailService orderDetailService;

    @Override
    public void submit(Orders orders) {

        //获得当前用户id
        Long userId = BaseContext.getThreadLocal();
        //根据ID查购物车
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);

//        //如果购物车为空
//        if (shoppingCartList == null) {
//            return;
//        }

        //不为空,补充信息
//        //获得购物车amount
//        BigDecimal amount = BigDecimal.valueOf(0);
//        for (ShoppingCart shoppingCart : shoppingCartList) {
//            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
//            BigDecimal amount1 = shoppingCart.getAmount();
//            amount = number.multiply(amount1).add(amount);
//        }

        //AddressBookId
        LambdaQueryWrapper<AddressBook> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(AddressBook::getUserId, userId)
                .eq(orders.getAddressBookId() == null, AddressBook::getIsDefault, 1)
                .eq(orders.getAddressBookId() != null, AddressBook::getId, orders.getAddressBookId());
        AddressBook addressBook = addressBookService.getOne(lqw2);

        //User
        LambdaQueryWrapper<User> lqw3 = new LambdaQueryWrapper<>();
        lqw3.eq(User::getId, userId);
        User user = userService.getOne(lqw3);


        //以下补充信息,由OrdersDto接收,先填充Order部分
        //Orders->OrdersDto
        OrdersDto ordersDto = new OrdersDto();

        //以下为OrderDetail部分
        //OrderDetail与购物车相关联

        long orderId = IdWorker.getId();
        BigDecimal amount = new BigDecimal(0);//总价

        List<OrderDetail> orderDetails = shoppingCartList.stream().map(
                ((shoppingCart) -> {
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(shoppingCart, orderDetail);
                    // orderId单独设置
                    orderDetail.setOrderId(orderId);
                    // amount 金额单独设置 数量  *  单价
                    BigDecimal price = shoppingCart.getAmount();
                    BigDecimal number = new BigDecimal(shoppingCart.getNumber());

                    orderDetail.setAmount(price.multiply(number));

                    orderDetail.setOrderId(orderId);

                    orderDetailService.save(orderDetail);
                    return orderDetail;
                })
        ).collect(Collectors.toList());

        for (OrderDetail orderDetail : orderDetails) {
            BigDecimal amount1 = orderDetail.getAmount();
            amount=amount.add(amount1);
        }

        ordersDto.setOrderDetails(orderDetails);


        //ID自增
        //订单号?
        ordersDto.setNumber(String.valueOf(orderId));

        //订单状态默认1
        ordersDto.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        //设置用户id
        ordersDto.setUserId(userId);
        //设置AddressBookId
        ordersDto.setAddressBookId(addressBook.getId());
        //设置OrderTime
        ordersDto.setOrderTime(LocalDateTime.now());
        //设置CheckOutTime,如果支付成功
        ordersDto.setCheckoutTime(LocalDateTime.now());
        //设置payMethod
        ordersDto.setPayMethod(orders.getPayMethod());
        //设置总价格amount
        ordersDto.setAmount(amount);
        //设置remake
        ordersDto.setRemark(orders.getRemark());
        ordersDto.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址
        //设置username
        ordersDto.setUserName(user.getName());
        //设置Consignee
        ordersDto.setConsignee(addressBook.getConsignee());
        ordersDto.setPhone(addressBook.getPhone());//收货人联系电话

        this.save(ordersDto);

        // 6、删除当前用户的购物车数据
        // delete from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(qw1);

    }




}
